package com.jic.market.impl.rest.realtimeprice.realTimePriceHandler;

import com.google.common.base.Splitter;
import com.jic.market.common.enums.DeleteFlagEnum;
import com.jic.market.entity.GoodsPriceAndStock;
import com.jic.market.entity.PromotionEntity;
import com.jic.market.entity.PromotionSingleRuleEntity;
import com.jic.market.enums.FrontPromotionTypeEnum;
import com.jic.market.mapper.PromotionSingleRuleEntityMapper;
import com.jic.market.model.RealTimePriceContent;
import com.jic.market.response.rest.realtimeprice.RealTimePriceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * description: StraightDownRealTimePriceHandler-直降
 * date: 2020/4/10 15:16
 * author: wangys
 * version: 1.0
 */
@Component
public class StraightDownRealTimePriceHandler implements BaseRealTimePriceHandler {

    @Autowired
    PromotionSingleRuleEntityMapper promotionSingleRuleEntityMapper;

    @Override
    public Integer handlerFrontType() {
        return FrontPromotionTypeEnum.SINGLELY_FALL.getCode();
    }

    @Override
    public String apply(PromotionEntity promotionEntity, GoodsPriceAndStock goodsPriceAndStock) {
        Long mpId = goodsPriceAndStock.getId();
        Integer goodType = goodsPriceAndStock.getGoodType();
        String marketPrice = goodsPriceAndStock.getMarketPrice();

        PromotionSingleRuleEntity singleRuleEntity = new PromotionSingleRuleEntity();
        singleRuleEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        singleRuleEntity.setPromotionId(promotionEntity.getId());
        singleRuleEntity.setMpId(mpId);
        singleRuleEntity.setTypeOfProduct(goodType);
        PromotionSingleRuleEntity promotionSingleRuleEntity = promotionSingleRuleEntityMapper.query(singleRuleEntity);
        if(promotionSingleRuleEntity == null){
            return null;
        }
        if(marketPrice.contains("~")){
            marketPrice = Splitter.on("~").splitToList(marketPrice).get(0);
        }
        return new BigDecimal(marketPrice).subtract(promotionSingleRuleEntity.getContentValue()).toString();
    }

    @Override
    public void accept(RealTimePriceContent realTimePriceContent) {
        RealTimePriceResponse realTimePriceResponse = realTimePriceContent.getRealTimePriceResponse();
        GoodsPriceAndStock goodsPriceAndStock = realTimePriceContent.getGoodsPriceAndStock();
        realTimePriceResponse.setAvailablePrice(apply(realTimePriceContent.getPromotionEntity(), goodsPriceAndStock));
    }
}
